//
//  MainClassViewController.m
//  B项目
//
//  Created by 陶志福 on 15/12/16.
//  Copyright © 2015年 tzf. All rights reserved.
//

#import "MainClassViewController.h"
#import "MainClassTableViewController.h"
#import "SCNavTabBarController.h"
#import "MainClass.h"
#import "HotCollectionViewController.h"
#import "AppDelegate.h"
#import "MenuView.h"
#import "CollectGiftViewController.h"
#import "MainClassDetail.h"
#import "WebViewController.h"
#import "CollectTableViewController.h"
#import "SDImageCache.h"
#import "SharkOffViewController.h"
#import "SweepViewController.h"



#import "ChooseGift.h"
@interface MainClassViewController ()

@property (nonatomic,strong) NSMutableArray *nameArray;
@property (nonatomic,strong) NSMutableArray *idArray;

@property (nonatomic,strong) NSMutableArray *vcArray;

@property (nonatomic,strong) HotCollectionViewController *hotCollectionVC;

@property (nonatomic,strong) UIViewController *viewC;

@property (nonatomic,strong) MainClassTableViewController *mainClassTVC;

@property(nonatomic, strong) NSMutableArray *dataArray;//要展示的数据

@property (nonatomic, strong) NSMutableArray *searchResultDataArray;  // 存放搜索结果的数组

@property (copy, nonatomic) NSString *cache; // 当前缓存


@end

@implementation MainClassViewController

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSMutableArray *)idArray{
    if (!_idArray) {
        _idArray = [[NSMutableArray alloc]init];
    }
    return _idArray;
}

- (void)setData
{
    NSURL *url = [NSURL URLWithString:kMainClass];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if (data == nil) {
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"网络连接" message:@"似乎与互联网断开链接" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
    }else
    {
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
        ChooseGift *mainClass = [[ChooseGift alloc] init];
        
//        [LORequestManger GET:kMainClass success:^(id response) {
//            NSDictionary *Dic = (NSDictionary *)response;
//            
//            NSDictionary *dic1 = [Dic objectForKey:@"data"];
//            
//            _nameArray = [NSMutableArray array];
//            for (NSDictionary *dic2 in dic1[@"candidates"]) {
//                
//                MainClass *mainClass = [[MainClass alloc] init];
//                
//                [mainClass setValuesForKeysWithDictionary:dic2];
//                
//                [_nameArray addObject:mainClass];
//                
//            }
//            [self setController];
//            
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"%@",error);
//        }];
    
        
        NSDictionary *dic1 = [Dic objectForKey:@"data"];
        
        _nameArray = [NSMutableArray array];
        for (NSDictionary *dic2 in dic1[@"candidates"]) {
            
            ChooseGift *mainClass = [[ChooseGift alloc] init];
            
            [mainClass setValuesForKeysWithDictionary:dic2];
            
            [_nameArray addObject:mainClass];
            
        }
        [self setController];
    }

    
    
}

- (void)setController
{
    SCNavTabBarController *navTabBarController = [[SCNavTabBarController alloc] init];
    _vcArray = [NSMutableArray  array];
    
    for (int i = 0; i < [_nameArray count]; i ++) {
        
        _mainClassTVC = [[MainClassTableViewController alloc] init];
        
        _mainClassTVC.title = [_nameArray[i] name];
        
        _mainClassTVC.ID = [_nameArray[i] ID];
        [_vcArray addObject:_mainClassTVC];
    }
    navTabBarController.subViewControllers = _vcArray;
    navTabBarController.showArrowButton = YES;
    [navTabBarController addParentController:self];
    
}



- (void)viewDidLoad {
    [self setData];
    
    [self setHidesBottomBarWhenPushed:NO];

    

    self.title = @"礼卿";
    
    // 搜索按钮
    UIBarButtonItem *searchBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBarButtonItemAction)];
    self.navigationItem.rightBarButtonItem = searchBarButtonItem;
    
    self.dataArray = [NSMutableArray array];
    self.searchTVC = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    self.searchTVC.tableView.delegate = self;
    self.searchTVC.tableView.dataSource = self;
    [self.searchTVC.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

    // Do any additional setup after loading the view.
  
    
    
    
    
    _sideSlipView = [[JKSideSlipView alloc]initWithSender:self];
    _sideSlipView.backgroundColor = [UIColor redColor];
    
    MenuView *menu = [MenuView menuView];
    [menu didSelectRowAtIndexPath:^(id cell, NSIndexPath *indexPath) {
       
        if (indexPath.row == 0) {
            CollectGiftViewController *collect = [[CollectGiftViewController alloc]init];
//            [self setHidesBottomBarWhenPushed:YES];

            [self.navigationController pushViewController:collect animated:YES];
            
        }
        if (indexPath.row == 1) {
            CollectTableViewController *collect = [[CollectTableViewController alloc]init];

            [self.navigationController pushViewController:collect animated:YES];
            
        }
        if (indexPath.row == 2) {
            SweepViewController *sw = [[SweepViewController alloc]init];

            [self.navigationController pushViewController:sw animated:YES];
            
            
        }
        if (indexPath.row == 3) {
            SharkOffViewController *share = [[SharkOffViewController alloc]init];

            [self.navigationController pushViewController:share animated:YES];
            
        }
        if (indexPath.row == 4) {
            dispatch_async(
                           dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                           , ^{
                               [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});

        }

        if (indexPath.row == 5) {
            [_sideSlipView hide];
            
        }

        
        
        
        
        
        //            [_sideSlipView hide];

    }];
    menu.items = @[@{@"title":@"收藏的礼物",@"imagename":@"main3.gif"},@{@"title":@"收藏的攻略",@"imagename":@"gl.gif"},@{@"title":@"扫一扫",@"imagename":@"sweep.jpg"},@{@"title":@"摇一摇选礼物",@"imagename":@"share2.jpg"},
  @{@"title":@"清除缓存",@"imagename":@"123.gif"},@{@"title":@"退出",@"imagename":@"main2.gif"}];
    [_sideSlipView setContentView:menu];
    [self.view addSubview:_sideSlipView];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(push)];
    
  
    
    
    
}

- (void)push{
    [_sideSlipView switchMenu];

}
-(void)clearCacheSuccess

{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"当前缓存:%@",[self returnCurrentCache]] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"清除", nil];
    alert.delegate = self;
    
    [alert show];
    
}
- (NSString *)returnCurrentCache
{
    float tmpSize = [[SDImageCache sharedImageCache] checkTmpSize];
    
    NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"(%.2fM)",tmpSize] : [NSString stringWithFormat:@"(%.2fK)",tmpSize * 1024];
    
    
    //清理
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    
    for (NSString *p in files) {
        
        NSError *error;
        
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    [[SDImageCache sharedImageCache] clearDisk];
    
    [[SDImageCache sharedImageCache] clearMemory];//可有可无
    
    return clearCacheName;
}

#pragma mark-
#pragma mark  搜索按钮

- (void)searchBarButtonItemAction
{
    // 使用表示图控制器创建出搜索控制器
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchTVC];
    // 搜索框检测代理
    //（这个需要遵守的协议是 <UISearchResultsUpdating> ，这个协议中只有一个方法，当搜索框中的值发生变化的时候，代理方法就会被调用）
    _searchController.delegate = self;
    _searchController.searchResultsUpdater = self;
    _searchController.searchBar.delegate = self;
    _searchController.searchBar.placeholder = @"选份礼物给心目中最爱的那个人";
    _searchController.searchBar.prompt = @"输入要查找的内容";
//    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    [self.searchController.searchBar sizeToFit];
    
    // 因为搜索是控制器，所以要使用模态推出（必须是模态，不可是push）
    
    [self presentViewController:self.searchController animated:YES completion:nil];
}

#pragma mark - UITableViewDataSource Method 数据源方法
// 设置分组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//设置分组中的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

//设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}


// 设置每个cell上显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    //  设置cell要显示的信息
    cell.textLabel.text = [_dataArray objectAtIndex:indexPath.row];
    
    return cell;
}



#pragma mark - UITableViewDelegate Methods
#pragma mark 处理cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewController *webViewVC = [[WebViewController alloc] init];
    
    webViewVC.userid = [_searchResultDataArray[indexPath.row] ID];
    
    webViewVC.style = 200;
    webViewVC.type = 1;

    webViewVC.choosegift = _nameArray[indexPath.row];
    [_searchTVC dismissViewControllerAnimated:YES completion:nil];
    
    [webViewVC setHidesBottomBarWhenPushed:YES];
    
    [self.navigationController pushViewController:webViewVC animated:YES];

    

}


#pragma mark - UISearchResultsUpdating Method
#pragma mark 监听者搜索框中的值的变化
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = [self.searchController.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [[kGift1 stringByAppendingString:searchString] stringByAppendingString:kGift2];
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *Dic = (NSDictionary *)response;
        
        NSArray *titleArray = Dic[@"data"][@"items"];
        
        _searchResultDataArray = [[NSMutableArray alloc] init];
        [_dataArray removeAllObjects];
        for (NSDictionary *dic in titleArray) {
            NSString *name = dic[@"name"];
            NSString *price = dic[@"price"];
            NSString *favorites_count = dic[@"favorites_count"];
            NSString *cellText = [NSString stringWithFormat:@"%@,💰:%@，❤️:%@",name,price,favorites_count];
            
            MainClassDetail *mainDetail = [[MainClassDetail alloc] init];
            
            [mainDetail setValuesForKeysWithDictionary:dic];
            
            [_searchResultDataArray addObject:mainDetail];
            
            [_dataArray addObject:cellText];
            
        }
        [_searchTVC.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
    
}

//
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    
    // 1. 获取输入的值
    NSString *queryString = searchBar.text;
    NSLog(@"%@",queryString);
    //进入通用页面
    _viewC = [[UIViewController alloc] init];
    
    _hotCollectionVC = [[HotCollectionViewController alloc] initWithCollectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
    _hotCollectionVC.type = @"搜索框1";
    _hotCollectionVC.ID = queryString;
    
    
    // 2. 添加攻略模块
    _mainClassTVC = [[MainClassTableViewController alloc] initWithStyle:UITableViewStylePlain];
    _mainClassTVC.ID = queryString;
    _mainClassTVC.type = @"搜索框";
    
    
    [_viewC.view addSubview:_hotCollectionVC.view];
    [_viewC addChildViewController:_hotCollectionVC];
    
    
    UISegmentedControl *segCtr;
    segCtr = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"礼物",@"攻略",nil]];
    segCtr.tintColor = [UIColor whiteColor];
    [segCtr addTarget:self action:@selector(changeValueAction:) forControlEvents:UIControlEventValueChanged];
    segCtr.selectedSegmentIndex = 0;
    _viewC.navigationItem.titleView = segCtr;
    
    [self.searchController dismissViewControllerAnimated:YES completion:nil];
    
    [_viewC setHidesBottomBarWhenPushed:YES];
    
    [self.navigationController pushViewController:_viewC animated:YES];
    
}

//分段空间触发方法
- (void)changeValueAction:(UISegmentedControl *)segmentedControl
{
    //判断当前选中空间的下标
    switch (segmentedControl.selectedSegmentIndex) {
        case 0:
            // 1. 移除攻略模块
            [_mainClassTVC.view removeFromSuperview];
            [_mainClassTVC removeFromParentViewController];
            
            // 2. 添加礼物模块
            [_viewC.view addSubview:_hotCollectionVC.view];
            [_viewC addChildViewController:_hotCollectionVC];
            [_viewC.view sendSubviewToBack:_hotCollectionVC.view];
            break;
        case 1:
            // 1. 移除礼物模块
            [_hotCollectionVC.view removeFromSuperview];
            [_hotCollectionVC removeFromParentViewController];
            
            
            [_viewC.view addSubview:_mainClassTVC.view];
            [_viewC addChildViewController:_mainClassTVC];
            [_viewC.view sendSubviewToBack:_mainClassTVC.view];
            _mainClassTVC.tableView.frame = CGRectMake(0, 66, kWidth, kHeight - 66);
            
            break;
            
        default:
            break;
    }
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.searchController.searchBar setHidden:YES];
    //[self setTabBarHidden:NO withAnimation:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
